package com.gitee.wsl.mathematics.geometry.d2.line.ext

import com.gitee.wsl.mathematics.coordinate.d2.Coordinate2
import com.gitee.wsl.mathematics.coordinate.d2.Point2
import com.gitee.wsl.mathematics.geometry.d2.line.LineShape2d
import com.gitee.wsl.mathematics.vector.ext.distanceTo
import com.gitee.wsl.mathematics.vector.ext.dot
import com.gitee.wsl.mathematics.vector.ext.minus
import com.gitee.wsl.mathematics.vector.ext.squaredDistanceTo

fun<T:Number,V:Coordinate2<T,V>> LineShape2d<T, V>.getMinimumDistance(p: Point2<T,*>): T{
    val v = a
    val w = b
    val l2 = v.squaredDistanceTo(w)
    if (l2 == 0.0) return p.squaredDistanceTo(a)
    val t = clamp((((p - v) dot  (w - v)) / l2),zero, one)
    return p.distanceTo(v + (w - v) * t)
}